package ltd.dujiabao.springcloud.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.springcloud.entities.CommonResult;
import ltd.dujiabao.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * @author : DuJiabao
 * @Project : springcloud
 * @Time : 2021/5/21 13:07
 * @Desc :
 */
@Api("订单处理")
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
  @Autowired
  RestTemplate restTemplate;
  @Value("${payment.url}")
  String paymentUrl;

  @GetMapping("/payment/get/{id}")
  public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
    CommonResult<Payment> result = restTemplate.getForObject(paymentUrl + "/payment/get/" + id, CommonResult.class);
    log.info("Order 查询 Payment，id：" + id);
    return result;
  }

  @PostMapping("/payment/create")
  public CommonResult createPayment(@RequestBody Payment payment) {
    CommonResult result = restTemplate.postForObject(paymentUrl + "/payment/create/", payment, CommonResult.class);
    log.info("Order 添加 Payment，url为: " + payment.toString());
    return result;
  }

  @GetMapping("/payment/getEntity/{id}")
  public CommonResult<Payment> getPaymentEntityById(@PathVariable("id") Long id) {
    ResponseEntity<CommonResult> entity = restTemplate.getForEntity(paymentUrl + "/payment/get/" + id, CommonResult.class);
    log.info("获取到的信息是：" + entity.toString());
    log.info("获取到的StatusCode是：" + entity.getStatusCode());
    log.info("获取到的StatusCodeValue是：" + entity.getStatusCodeValue());
    log.info("获取到的Headers是：" + entity.getHeaders());

    if (entity.getStatusCode().is2xxSuccessful()) {
      log.info("查询成功：" + id);
      return entity.getBody();
    } else {
      log.info("查询失败：" + id);
      return new CommonResult<>(CommonResult.FAIlURE, "查询失败");
    }
  }
}
